﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using TSComm.Utilities.Sys;

namespace JSTT_DATAPROCESS_SERVICE
{
    public partial class JSTTProcessService : ServiceBase
    {
        private JSTT.DataThreadProcess.THRecieveDevDatas revDevDatas = new JSTT.DataThreadProcess.THRecieveDevDatas();
        private JSTT.DataThreadProcess.THProcessDeviceData processDeviceData = new JSTT.DataThreadProcess.THProcessDeviceData();

        private Thread thRecivedSocketData = null;
        private Thread thProcessMessageData = null;

        private Timer timerThreadProcess = null;
        private string eventSource = "JSTTDataProcessService";
        //private SysEvent sysEvent;

        public JSTTProcessService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            JSTTLogger.Logger.ProcInfoLogger("JSTTDataProcessService:Service Start");
            // 频率3分钟更新数据表一次
            int timeRate = Convert.ToInt16(System.Configuration.ConfigurationManager.AppSettings["PROCESSWAITINGTIME"].ToString());
            timerThreadProcess = new System.Threading.Timer(processDeviceData.DataProcessTimeAction, null, TimeSpan.FromSeconds(20), TimeSpan.FromMinutes(timeRate));

            // 接收数据的线程，负责Socket数据接收
            thRecivedSocketData = new Thread(revDevDatas.ReceiveSocketDatas);
            thRecivedSocketData.Name = "ReciveMessageData";
            thRecivedSocketData.Start();

            // 处理数据的线程，负责数据的处理
            thProcessMessageData= new Thread(processDeviceData.ReceiveMessages);
            thProcessMessageData.Name = "ProcessMessageData";
            thProcessMessageData.Start();
            
            // Service代码不需要join
            //thRecivedSocketData.Join();
            //thProcessMessageData.Join();
        }

        protected override void OnStop()
        {
            if (thRecivedSocketData != null && thRecivedSocketData.ThreadState == System.Threading.ThreadState.Running)
            {
                thRecivedSocketData.Abort();
                JSTTLogger.Logger.ProcInfoLogger("JSTTDataProcessService:ReciveMessageData Thread Quit.");
            }

            if (thProcessMessageData != null && thProcessMessageData.ThreadState == System.Threading.ThreadState.Running)
            {
                thProcessMessageData.Abort();
                JSTTLogger.Logger.ProcInfoLogger("JSTTDataProcessService:thProcessMessageData Thread Quit.");
            }
            //timerThreadProcess.Change()
            timerThreadProcess.Dispose();

            JSTTLogger.Logger.ProcInfoLogger("JSTTDataProcessService:Service End");
        }
    }
}
